package com.lxh.lxhcrm.model.service;

import com.lxh.lxhcrm.model.dao.FunctionDao;
import com.lxh.lxhcrm.model.dao.PositionDao;
import com.lxh.lxhcrm.model.mappers.funTy.FunTyMapper;
import com.lxh.lxhcrm.model.pojos.Function;
import com.lxh.lxhcrm.model.pojos.FunctionType;
import com.lxh.lxhcrm.model.pojos.Position;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Service
@Transactional(rollbackFor = Exception.class)
public class FunTyService {
    @Autowired
    FunTyMapper funTyMapper;
    @Autowired
    PositionDao positionDao;
    @Autowired
    FunctionDao functionDao;
    /*根据权限组id查询 所有的权限*/
    public List<Function> findFunByFunTyId(String funTypeName){
        return funTyMapper.findFunByFunTyId(funTypeName);
    }
    /*根据职位id 查询 该权限组已被选的权限*/
    public  List<Integer> findFunByPostId(Integer positionId,String funTypeName){
        return funTyMapper.findFunByPostId(positionId,funTypeName);
    }
    public List<FunctionType> funMenu(Integer empId,Integer positionId){
    return funTyMapper.funMenu(empId,positionId);
    }
    /*根据前台传过来的员工id查询部门id*/
    public Integer findDeptId(Integer empId){
        return funTyMapper.findDeptId(empId);
    }
    /*根据前台传来的员工id查询职位id*/
    public Integer findPoId(Integer empId){
        return funTyMapper.findPoId(empId);
    }
/*保存权限*/
    public void saveQuan(Integer positionId,String funTypeName,  List<Integer> funId) {

        Position position = positionDao.findById(positionId).get();
        System.out.println("职位权限开始操作");
        List<Function> funIds =funTyMapper.EditFuns(positionId,funTypeName);
        System.out.println(funIds+"funIds");

        List<Integer> list = new ArrayList<Integer>();
        for (int i=0;i<funIds.size();i++){
           list.add(funIds.get(i).getFunctionId());
        };
        System.out.println(list+"list1");
        list.addAll(funId);
        System.out.println(list+"list2");

        List<Function> fun=position.getFunctions();
        System.out.println("funxxx"+fun);
        if(fun == null){
            fun = new ArrayList<Function>();
        }
        fun.clear();//先清空

        //给集合添加数据，给表新增记录,已有的funId（除去选择的权限组下面的）  加上现在选择的ID
        fun.addAll((Collection)functionDao.findAllById(list));
        //重置集合，相当于执行中间表新增
        position.setFunctions(fun);
    }
    /*查询是否有修改权限组权限*/
    public List<String> checkFunTy(Integer empId){
        return funTyMapper.checkFunTy(empId);
    }
}
